package com.pinyoumei.app.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.wallet.RechargeActivity;
import com.pinyoumei.app.bean.EPayBean;
import com.pinyoumei.app.bean.RechargeBean;
import com.pinyoumei.app.bean.WxPayEntity;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.PayUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.event.AlipayEvent;
import com.pinyoumei.app.view.LoadingDailog;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2021-08-27.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-27        Administrator             新增Person类
 * 2021-08-27        Administrator             增加sex属性
 * 余额充值
 */
public class BalanceActivity extends AppCompatActivity implements View.OnClickListener {

    private LinearLayout ll_1;
    private TextView tv_1;
    private LinearLayout ll_2;
    private TextView tv_2;
    private LinearLayout ll_3;
    private TextView tv_3;
    private LinearLayout ll_4;
    private TextView tv_4;
    private CheckBox checkbox_zhifubao;
    private CheckBox checkbox_wechat;
    private TextView tv_user_balance;
    private int pay_type = 2;
    private int amount_type = 1;
    protected AppManager appManager = AppManager.getInstance();
    private Gson gson;
    private LoadingDailog loadingDailog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtils.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明
        StatusBarUtils.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtils.setStatusBarDarkTheme(this, true)){
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtils.setStatusBarColor(this,0x55000000);
        }
        // 添加activity 到栈
        appManager.addActivity(this);

        gson = new Gson();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        setContentView(R.layout.activity_balance);
        EventBusUtils.register(this);

        InitWidget();

        InitData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEventMain(AlipayEvent event) {
            //订单详情
            if (event!=null){
                Intent intent = new Intent(BalanceActivity.this, BalanceOrderListActivity.class);
                startActivity(intent);
                finish();

            }
            EventBusUtils.removeStickyEvent( AlipayEvent.class);


    }

    private void InitWidget() {
        RelativeLayout relative_finish = findViewById(R.id.relative_finish);
        relative_finish.setOnClickListener(this);
        RelativeLayout rl_1 = findViewById(R.id.rl_1);
        rl_1.setOnClickListener(this);
        RelativeLayout rl_recharge = findViewById(R.id.rl_recharge);
        rl_recharge.setOnClickListener(this);
        RelativeLayout rl_2 = findViewById(R.id.rl_2);
        rl_2.setOnClickListener(this);
        Button bt_submit = findViewById(R.id.bt_submit);
        bt_submit.setOnClickListener(this);
        tv_user_balance = findViewById(R.id.tv_user_balance);
        checkbox_zhifubao = findViewById(R.id.checkbox_zhifubao);
        checkbox_wechat = findViewById(R.id.checkbox_wechat);

        ll_1 = findViewById(R.id.ll_1);
        ll_1.setOnClickListener(this);
        tv_1 = findViewById(R.id.tv_1);

        ll_2 = findViewById(R.id.ll_2);
        ll_2.setOnClickListener(this);
        tv_2 = findViewById(R.id.tv_2);

        ll_3 = findViewById(R.id.ll_3);
        ll_3.setOnClickListener(this);
        tv_3 = findViewById(R.id.tv_3);

        ll_4 = findViewById(R.id.ll_4);
        ll_4.setOnClickListener(this);
        tv_4 = findViewById(R.id.tv_4);


    }

    private void initSelect() {
        ll_1.setBackground(ContextCompat.getDrawable(BalanceActivity.this,R.drawable.shanpe_gray_corner_5dp));
        ll_2.setBackground(ContextCompat.getDrawable(BalanceActivity.this,R.drawable.shanpe_gray_corner_5dp));
        ll_3.setBackground(ContextCompat.getDrawable(BalanceActivity.this,R.drawable.shanpe_gray_corner_5dp));
        ll_4.setBackground(ContextCompat.getDrawable(BalanceActivity.this,R.drawable.shanpe_gray_corner_5dp));

        tv_1.setTextColor(ContextCompat.getColor(BalanceActivity.this,R.color.text_gray2));
        tv_2.setTextColor(ContextCompat.getColor(BalanceActivity.this,R.color.text_gray2));
        tv_3.setTextColor(ContextCompat.getColor(BalanceActivity.this,R.color.text_gray2));
        tv_4.setTextColor(ContextCompat.getColor(BalanceActivity.this,R.color.text_gray2));
    }

    private void InitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(BalanceActivity.this));

        OkGo.<String>post(Constants.MY_RECHARGE)
                .params("user_id", SPUtils.getAppUserId(BalanceActivity.this))
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        RechargeBean rechargeBean = gson.fromJson(response.body(), RechargeBean.class);

                        if (rechargeBean.getCode() >= 0) {
                            tv_user_balance.setText(rechargeBean.getResult().getUser_balance()+"");
                        } else {
                            Toast.makeText(BalanceActivity.this, rechargeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });
    }




    private void SubmitData() {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", SPUtils.getAppUserId(BalanceActivity.this));
        map.put("pay_type", pay_type);
        map.put("amount_type", amount_type);


        OkGo.<String>post(Constants.MY_RECHARGE_SUBMIT)
                .params("user_id", SPUtils.getAppUserId(BalanceActivity.this))
                .params("pay_type", pay_type)
                .params("amount_type", amount_type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        EPayBean agencyRuleBean = gson.fromJson(response.body(), EPayBean.class);
                        if (agencyRuleBean.getCode() > 0 ){
                            switch (pay_type) {
                                case 1:
                                    //微信支付
                                    IWXAPI wxapi = WXAPIFactory.createWXAPI(BalanceActivity.this, SPUtils.getWxKey(BalanceActivity.this));
                                    PayUtils payUtils = new PayUtils(wxapi,BalanceActivity.this, agencyRuleBean.getResult().getPartner_id());
                                    WxPayEntity wxPayEntity = new WxPayEntity();
                                    wxPayEntity.setPrepay_id(agencyRuleBean.getResult().getPrepay_id());
                                    wxPayEntity.setNoncestr(agencyRuleBean.getResult().getNonce_str());
                                    wxPayEntity.setTimestamp(agencyRuleBean.getResult().getTime_stamp());
                                    wxPayEntity.setSign(agencyRuleBean.getResult().getSign());
                                    payUtils.payByWechat(wxPayEntity);
                                    break;
                                case 2:
                                    //支付宝
                                    //需要跳进支付宝H5支付页面
                                    String url = agencyRuleBean.getResult().getAli_pay_url();
                                    if (TextUtils.isEmpty(url)) {
                                        ToastUtils.showShort("支付链接为空");
                                        finish();//一旦出现支付失败订单提交界面得销毁 订单作废 因为不能重复提交同一订单
                                        return;
                                    }

                                    Intent intent = new Intent(BalanceActivity.this, WebViewActivity.class);
                                    intent.putExtra("url", url);
                                    intent.putExtra("order_title", "正在支付");
                                    startActivity(intent);
//                                    h5Pay(url);
                                    break;
                                default:
                                    break;
                            }

                        }else{
                            ToastUtils.showShort(agencyRuleBean.getMsg());
                        }
                    }

                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        	case R.id.relative_finish:
        		finish();
        		break;
                case R.id.rl_recharge:
                startActivity(new Intent(BalanceActivity.this, RechargeActivity.class));
                break;
        		case R.id.ll_1:
                    amount_type = 1;
                    initSelect();
                    ll_1.setBackground(ContextCompat.getDrawable(BalanceActivity.this,R.drawable.shanpe_green_corner_5dp));
                    tv_1.setTextColor(ContextCompat.getColor(BalanceActivity.this,R.color.green_bg2));
                    break;

        		case R.id.ll_2:
                    amount_type = 2;
                    initSelect();
                    ll_2.setBackground(ContextCompat.getDrawable(BalanceActivity.this,R.drawable.shanpe_green_corner_5dp));
                    tv_2.setTextColor(ContextCompat.getColor(BalanceActivity.this,R.color.green_bg2));
        		break;

        		case R.id.ll_3:
                    amount_type = 3;
                    initSelect();
                    ll_3.setBackground(ContextCompat.getDrawable(BalanceActivity.this,R.drawable.shanpe_green_corner_5dp));
                    tv_3.setTextColor(ContextCompat.getColor(BalanceActivity.this,R.color.green_bg2));
        		break;
        		case R.id.ll_4:
                    amount_type = 4;
                    initSelect();
                    ll_4.setBackground(ContextCompat.getDrawable(BalanceActivity.this,R.drawable.shanpe_green_corner_5dp));
                    tv_4.setTextColor(ContextCompat.getColor(BalanceActivity.this,R.color.green_bg2));
        		break;
	            case R.id.rl_1:
                    checkbox_zhifubao.setChecked(false);
                    checkbox_wechat.setChecked(true);
                    pay_type = 1;
        		break;

            case R.id.rl_2:
                checkbox_zhifubao.setChecked(true);
                checkbox_wechat.setChecked(false);
                pay_type = 2;
                break;

                case R.id.bt_submit:
                    SubmitData();
                break;
        	default:
        		break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }
}
